package com.qiantu.phone.widget.setting;

import static android.util.TypedValue.COMPLEX_UNIT_PX;

import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.hjq.base.DensityUtils;
import com.hjq.http.listener.HttpCallback;
import com.hjq.widget.layout.SettingBar;
import com.qiantu.api.db.LLControllerDBManager;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.entity.ControllerBean;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.KGXcollectionData;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.Request.KGXRequest;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.event.DeviceDetailChangeEvent;
import com.qiantu.phone.event.RefreshControllerEvent;
import com.qiantu.phone.ui.uiutil.CoorTools;
import com.qiantu.phone.utils.Constants;
import com.qiantu.phone.event.DeviceItemChangeEvent;
import com.qiantu.phone.ui.dialog.BottomEditDialog;
import com.lxj.xpopup.XPopup;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import okhttp3.Call;

public class DeviceSettingName extends SettingBar implements View.OnClickListener {
    private DeviceBean mDevice;
    private AppActivity mContext;
    public DeviceSettingName(AppActivity context, DeviceBean deviceBean) {
        this(context, null, deviceBean);
    }

    public DeviceSettingName(AppActivity context, AttributeSet attrs, DeviceBean deviceBean) {
        this(context, attrs, 0, deviceBean);
    }

    public DeviceSettingName(AppActivity context, AttributeSet attrs, int defStyleAttr, DeviceBean deviceBean) {
        this(context, attrs, defStyleAttr, R.style.setting_item_style, deviceBean);
    }

    public DeviceSettingName(@NonNull AppActivity context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes, DeviceBean deviceBean) {
        super(context, attrs, defStyleAttr, defStyleRes);
        mDevice = deviceBean;
        mContext = context;
        if(mDevice.getDeviceGroup() == 0){
            setLeftText(R.string.device_name);
        }else{
            setLeftText(R.string.device_group_name);
        }
        setRightText(mDevice.getName());
        setRightTextColor(AppApplication.getInstance().getThemeColor(R.attr.textColor2));
        setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        setRightTextSize(COMPLEX_UNIT_PX, DensityUtils.dip2px(context, 12));
        setOnClickListener(this::onClick);
    }

    BottomEditDialog mBottomEditDialog;
    private void showBottomEditDialog(String text) {
        if (mBottomEditDialog == null) {
            mBottomEditDialog = new BottomEditDialog(getContext());
            mBottomEditDialog.setLabel(getContext().getString(R.string.device_name));
            mBottomEditDialog.setHint(getContext().getString(R.string.please_enter_device_name));
            mBottomEditDialog.setDialogClickListener(new BottomEditDialog.DialogClickListener() {
                @Override
                public void onConfirmClick() {
                    mDevice.setName(mBottomEditDialog.getText());
                    updateDeviceName();
                }
            });
            new XPopup.Builder(getContext())
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomEditDialog);
        }
        mBottomEditDialog.setText(text);
        mBottomEditDialog.setMaxLength(Constants.DEVICE_NAME_MAX_LENGTH);
        mBottomEditDialog.show();
    }

    private void updateDeviceName() {
        HttpCallback<HttpData<Void>> callback = new HttpCallback<HttpData<Void>>(mContext) {
            @Override
            public void onStart(Call call) {
                mContext.showDialog(mContext.getString(R.string.modifying));
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                setRightText(mDevice.getName());
                LLDeviceDBManager.getInstance(getContext()).put(mDevice);
                EventBus.getDefault().post(new DeviceItemChangeEvent(mDevice.getRoomSerialNo(), mDevice.getDeviceSerialNo(), mDevice.getIsFavourite()));
                EventBus.getDefault().post(new DeviceDetailChangeEvent(mDevice.getDeviceSerialNo()));

                if(mDevice.getDeviceGroup() == 0){
                    if (mDevice.getDeviceType().contains("wall_switch")){
                        //修改控制器名字
                        updateCoorName();
                    }else {
                        mContext.toast(R.string.reset_success);
                    }
                }else {
                    mContext.toast(R.string.reset_success);
                }


            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }

            @Override
            public void onEnd(Call call) {
                mContext.hideDialog();
            }
        };
        if(mDevice.getDeviceGroup() == 0){
            LLHttpManager.modifyDevice(mContext, mDevice, callback);
        }else{
            LLHttpManager.modifyDeviceGroup(mContext, mDevice, callback);
        }
    }


    private void updateCoorName() {
        ControllerBean coor = LLControllerDBManager.getInstance(getContext()).getControllerBySerialNo(mDevice.getControllerSerialNo());
        if (coor !=null){
            if (coor.getProductModel().equals("0x1006")){//kgx
                getKGXControllers(mDevice.getName(),coor.getControllerSerialNo());
            }else {//普通从机
                updateControllerName(mDevice.getName(),coor.getControllerSerialNo());
            }
        }else {
            mContext.toast(R.string.reset_success);
        }
    }

    private void getKGXControllers(String name,String controllerSerialNo){
        LLHttpManager.getdevicecollectlist(mContext, controllerSerialNo, new HttpCallback<HttpData<List<KGXcollectionData>>>(mContext){
            @Override
            public void onStart(Call call) {
                super.onStart(call);
            }

            @Override
            public void onSucceed(HttpData<List<KGXcollectionData>> result) {
                super.onSucceed(result);
                if (result.getCode() == 10000){
                    List<KGXcollectionData> collectionDatas = result.getData();
                    updateKGXControllerName(name,controllerSerialNo,collectionDatas);

                } else {
                    mContext.toast(R.string.reset_success);;
                }

            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }

            @Override
            public void onEnd(Call call) {
                super.onEnd(call);
            }
        });
    }

    private void updateKGXControllerName(String name,String controllerSerialNo,List<KGXcollectionData> collectionDatas) {
        boolean isHave = false;
        KGXcollectionData needEditData = null;
        for (KGXcollectionData data:collectionDatas) {
            if (data.getDeviceCollectSerialNo().equals(mDevice.getDeviceCollectSerialNo())){
                isHave = true;
                needEditData = data;
                needEditData.setName(name);
                break;
            }
        }

        if (isHave){
            KGXRequest.editdevicecollectinfo(mContext,needEditData, new HttpCallback<HttpData<Void>>(mContext){
                @Override
                public void onStart(Call call) {}

                @Override
                public void onSucceed(HttpData<Void> result) {
                    mContext.toast(R.string.reset_success);
                }

                @Override
                public void onFail(Exception e) {
                    super.onFail(e);
                }

                @Override
                public void onEnd(Call call) {

                }
            });
        }else {
            mContext.toast(R.string.reset_success);
        }
    }
    private void updateControllerName(String name,String controllerSerialNo){
        LLHttpManager.updateControllerName(mContext, controllerSerialNo, name, new HttpCallback<HttpData<Void>>(mContext){
            @Override
            public void onStart(Call call) { };
            @Override
            public void onSucceed(HttpData<Void> result) {
                LLControllerDBManager.getInstance(getContext()).updateName(controllerSerialNo, name);
                EventBus.getDefault().post(new RefreshControllerEvent());
                mContext.toast(R.string.reset_success);
            }
            @Override
            public void onFail(Exception e) { super.onFail(e);};
            @Override
            public void onEnd(Call call) {mContext.hideDialog(); };
        });
    }

    @Override
    public void onClick(View v) {
        showBottomEditDialog(mDevice == null ? "" : mDevice.getName());
    }
}
